import { User } from '@/types/todo';

class AuthStore {
  private static instance: AuthStore;
  private user: User | null = null;
  private listeners: Array<(user: User | null) => void> = [];

  private constructor() {
    // 在构造函数中从 localStorage 恢复用户状态（仅在客户端）
    if (typeof window !== 'undefined') {
      this.loadUserFromStorage();
    }
  }

  static getInstance(): AuthStore {
    if (!AuthStore.instance) {
      AuthStore.instance = new AuthStore();
    }
    return AuthStore.instance;
  }

  getUser(): User | null {
    return this.user;
  }

  setUser(user: User | null): void {
    this.user = user;
    
    // 将用户信息存储到 localStorage 或从 localStorage 中删除（仅在客户端）
    if (typeof window !== 'undefined') {
      if (user) {
        localStorage.setItem('user', JSON.stringify(user));
      } else {
        localStorage.removeItem('user');
      }
    }
    
    this.notifyListeners();
  }

  subscribe(listener: (user: User | null) => void): () => void {
    this.listeners.push(listener);
    return () => {
      this.listeners = this.listeners.filter(l => l !== listener);
    };
  }

  private notifyListeners(): void {
    this.listeners.forEach(listener => listener(this.user));
  }

  isAuthenticated(): boolean {
    return !!this.user;
  }
  
  // 从 localStorage 加载用户信息
  private loadUserFromStorage(): void {
    try {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        this.user = JSON.parse(userStr);
      }
    } catch (error) {
      console.error('Failed to load user from storage:', error);
      // 如果解析失败，清除存储的用户信息
      localStorage.removeItem('user');
    }
  }
}

export const authStore = AuthStore.getInstance();